package com.integral.controller;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.weixin4j.WeixinException;
import org.weixin4j.http.HttpsClient;
import org.weixin4j.http.Response;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.integral.biz.ISignBiz;
import com.integral.biz.ISignItemBiz;
import com.integral.biz.ISignUserBiz;
import com.integral.entity.Sign;
import com.integral.entity.SignItem;
import com.integral.entity.SignUser;
import com.integral.entity.User;
import com.integral.util.StringUtils;
import com.integral.vo.OAuthJsToken;
import com.integral.vo.SignItemVo;
import com.integral.vo.SignVo;

@Controller
@RequestMapping("/signController")
public class SignController {
	
	@Resource
	private ISignBiz signBiz;
	@Resource
	private ISignUserBiz signUserBiz;
	@Resource
	private ISignItemBiz signItemBiz;
	
	//客户账号
    private static final String appid = "wx197baba861b048ea";	    //微信小程序appid
    private static final String secret = "bf9d6f795e9e0c7b4fc93cebf4f3787a";	//微信小程序密钥
    private static final String grant_type = "authorization_code";
	
    
    /**
	 * 获取登录信息
	 * @param code
	 * @param request
	 * @return
	 * @throws WeixinException
	 * @throws IOException
	 */
	@RequestMapping("/login")
    @ResponseBody
    public Map<String, Object> login(String code,String flag,HttpServletRequest request) throws WeixinException, IOException {
        if(!"1".equals(flag)){
        	throw new WeixinException("异常异常！！");
        }
		if (code == null || code.equals("")) {
            throw new WeixinException("invalid null, code is null.");
        }
        Map<String, Object> ret = new HashMap<String, Object>();
        //拼接参数
        String param = "?grant_type=" + grant_type + "&appid=" + appid + "&secret=" + secret + "&js_code=" + code;
        //创建请求对象
        HttpsClient http = new HttpsClient();
        //调用微信接口，获取openId以及sessionKey
        Response res = http.get("https://api.weixin.qq.com/sns/jscode2session" + param);
        //根据请求结果判定，是否验证成功
        JSONObject jsonObj = res.asJSONObject();
        if (jsonObj != null) {
            Object errcode = jsonObj.get("errcode");
            if (errcode != null) {
                //返回异常信息
                throw new WeixinException(errcode.toString());
            }

            ObjectMapper mapper = new ObjectMapper();
            OAuthJsToken oauthJsToken = mapper.readValue(jsonObj.toJSONString(),OAuthJsToken.class);
            String sessionKey = oauthJsToken.getSession_key();
            //解密sessionKey获取用户数据
//            try {
//                byte[] resultByte  = StringUtils.decrypt(Base64.decodeBase64(userSuperiorCode),    
//                        Base64.decodeBase64(oauthJsToken.getSession_key()),  
//                        Base64.decodeBase64(userSuperiorCode));    
//                    if(null != resultByte && resultByte.length > 0){    
//                        String userInfo = new String(resultByte, "UTF-8");                   
//                    }   
//            }catch (InvalidAlgorithmParameterException e) {    
//                    e.printStackTrace();    
//            } catch (UnsupportedEncodingException e) {    
//                    e.printStackTrace();    
//            }
            //设置用户（若用户存在，则返回用户信息。若用户不存在，则新增用户）
            SignUser signUser = signUserBiz.addSignUser(oauthJsToken.getOpenid());
            SignVo signVo = new SignVo();
    		signVo.setSignOpenId(oauthJsToken.getOpenid());
    		List<SignVo> signList = signBiz.findByPagination(signVo);
    		ret.put("signList", signList);
            ret.put("user", signUser);
        }
        return ret;
    }
	/*
	 * 用户授权成功后，修改用户昵称
	 */
	@RequestMapping(value="/updateUserName")
	@ResponseBody
	public String updateUserName(SignUser user){
		if(StringUtils.isEmpty(user.getUserOpenId())){
			return null;
		}
		//User wxUser = userBiz.findByCode(user.getUserCode());
		SignUser signUser = signUserBiz.findByUserOpenid(user.getUserOpenId());
		if(null == signUser){
			return null;
		}
		signUser.setUserName(user.getUserName());
		signUserBiz.updateSignUser(signUser);
		return "修改成功！";
	}
	
    /**
     * 新增打卡任务
     * @param signVo
     */
	@RequestMapping(value="/addSign")
	@ResponseBody
	public void addSign(SignVo signVo){
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat formatterymd = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		String nowData = formatterymd.format(new Date());
		Sign sign = new Sign();
		//打卡名称
		sign.setSignName(signVo.getSignName());
		//打卡类型
		sign.setSignType(signVo.getSignType());
		//打卡编码
		sign.setSignCode("S"+nowData+StringUtils.getRandomStringByLength(10));
		//用户唯一标识
		sign.setSignOpenId(signVo.getSignOpenId());
		//打卡保证金
		sign.setSignCashDeposit(signVo.getSignCashDeposit());
		//打卡次数
		sign.setSignNum(0);
		//开始、结束时间
		try {
			sign.setSignBeginDate(formatter.parse(signVo.getSignBeginDateString()+" 00:00:00"));
			sign.setSignEndDate(formatter.parse(signVo.getSignEndDateString()+" 00:00:00"));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		Long signBeginDate = sign.getSignBeginDate().getTime();
		Long nowDate = new Date().getTime();
		//如果当前时间大于开始时间 状态为进行中
		if(nowDate > signBeginDate){
			sign.setSignStatus(1);
		}else{
			sign.setSignStatus(3);
		}
		sign.setCreateTime(new Date());
		signBiz.addSign(sign);
		return;
	}
	/**
	 * 获取所有的打卡任务
	 * @param openId
	 * @return
	 */
	@RequestMapping(value="/findSignByOpenId")
	@ResponseBody
	public List<SignVo> findSignByOpenId(String openId){
		SignVo signVo = new SignVo();
		signVo.setSignOpenId(openId);
		List<SignVo> signList = signBiz.findByPagination(signVo);
		return signList;
	}
	/**
	 * 打卡次数+1
	 * @param signCode
	 */
	@RequestMapping(value="/sgin")
	@ResponseBody
	public String sgin(String signCode,String openId){
		//查询打卡任务
		SignVo signVo = signBiz.findBySignCode(signCode);
		//每日只能打一次卡校验 true:可以打卡    false:重复打卡，
		if(sginVerify(signCode, openId)){
			//创建打卡明细对象
			SignItem signItem = new SignItem();
			signItem.setSignCode(signCode);
			signItem.setSignOpenId(openId);
			signItem.setSignType(signVo.getSignType());
			signItem.setSignDate(new Date());
			signItem.setCreateTime(new Date());
			signItemBiz.addSignItem(signItem);
			//打卡次数+1
			signBiz.updateSignNumBySignCode(signCode);
		}else{
			return "今日已打过卡！";
		}
		return "打卡成功！";
	}
	
	/**
	 * 一天只能打一次卡，校验
	 * @param signCode
	 * @param openId
	 * @return
	 */
	public boolean sginVerify(String signCode,String openId ){
		//根据任务编码，用户编码获取到最新的打卡记录
		SignItemVo signItemVo = new SignItemVo();
		signItemVo.setSignCode(signCode);
		signItemVo.setSignOpenId(openId);
		List<SignItemVo> signItemList = signItemBiz.findByPagination(signItemVo);
		if(signItemList.isEmpty()){
			return true;
		}
		SignItemVo signItem = signItemList.get(0);
		//获取当天日期0点  和 23点59分59秒
		Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        Long begTime = calendar.getTime().getTime();
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
		Long endTime = calendar.getTime().getTime();
		Long createTime = signItem.getCreateTime().getTime();
		//如果最新的打卡记录创建时间在当天时间内，则禁止重复打卡
		if(begTime <= createTime && createTime <= endTime){
			return false;
		}
		return true;
	}
	/**
	 * 获取每日排行、总排行
	 * @return
	 */
	@RequestMapping(value="/allSign")
	@ResponseBody
	public Map<String,List<SignVo>> allSign(){
		Map<String,List<SignVo>> responseMap = new HashMap<String,List<SignVo>>();
		//获取总排行
		List<SignVo> signAll = signBiz.findSignAll();
		//获取每日排行
		List<SignVo> signToday = signBiz.findSignToday();
		responseMap.put("signAll", signAll);
		responseMap.put("signToday", signToday);
		return responseMap;
	}
}
